const express = require('express');
const multer = require('multer');
const path = require('path');
const cors = require('cors'); // Import cors

const app = express();
const port = 3001; // Use a different port than the frontend (e.g., 3000 or 5173)

// Enable CORS for all origins (for development purposes)
app.use(cors());

// Create 'uploads' directory if it doesn't exist
const uploadsDir = path.join(__dirname, 'uploads');
if (!require('fs').existsSync(uploadsDir)) {
    require('fs').mkdirSync(uploadsDir);
}

// Configure Multer for file storage
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadsDir); // Files will be stored in the 'uploads' directory
    },
    filename: function (req, file, cb) {
        // Use the original file name, but add a timestamp to prevent overwrites
        cb(null, Date.now() + path.extname(file.originalname));
    }
});

const upload = multer({ storage: storage });

// Serve static files from the 'uploads' directory
app.use('/uploads', express.static(uploadsDir));

// File upload endpoint
app.post('/upload', upload.single('image'), (req, res) => {
    if (!req.file) {
        return res.status(400).send('No file uploaded.');
    }
    // Return the URL where the file can be accessed
    const fileUrl = `http://localhost:${port}/uploads/${req.file.filename}`;
    res.json({ url: fileUrl });
});

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
});
